/* 
 COMP20007 Design of Algorithms 

 Read in a text string and split it into fragments of length
 k, overlapping by all but one chars.
 
 Output is k on first line, then one fragment per line.

 k-1 FIRST_CHAR are appended to the start of the string
 k-1 LAST_CHAR  are appended to the end of the string

 Subsititue all \n for NEWLINE_SUB

 Author: Andrew Turpin (aturpin@unimelb.edu.au)
 Date: April 2013

 Usage: ./makeInput k < filename
OR
 Usage: echo string | ./makeInput k

*/

#include <stdio.h>
#include <stdlib.h>

#define FIRST_CHAR 'Y'
#define LAST_CHAR  'Z'
#define NEWLINE_SUB  'N'

/*
** Print usage message
*/
void
usage(char *exeName) { 
    fprintf(stderr,"Usage: echo text | %s k\n",exeName);
    fprintf(stderr,"       where\n");
    fprintf(stderr,"          k - fragment length\n");
}

/*
** Read input, print output
*/
int 
main(int argc, char *argv[]) {
    if (argc != 2) {
        usage(argv[0]);
        return(EXIT_FAILURE);
    }

    int k;
    sscanf(argv[1], "%d", &k);

    printf("%d\n",k);

    int ch;
    char buff[k];

        // first fill buffer with k-1 FIRST_CHAR + one char from input
    for(int i = 0 ; i < k-1 ; i++)
        buff[i] = FIRST_CHAR;
    if ((ch = getchar()) == EOF) {
        fprintf(stderr,"Input too short. Must be at least k chars.");
        return EXIT_FAILURE;
    }
    buff[k-1] = ch;
    int nextChar = 0;

        // now loop printing buffer and sliding along one char
    int last_chars = k-1;
    while (last_chars >= 0) {
        for(int i = nextChar ; i < nextChar + k ; i++)
            putchar(buff[i % k]);
        putchar('\n');
        if ((ch = getchar()) == EOF) {
            ch = LAST_CHAR;
            last_chars--;
        }
        if (ch == '\n')
            ch = NEWLINE_SUB;
        buff[nextChar++] = ch;
        if (nextChar == k)
            nextChar = 0;
    }

    return EXIT_SUCCESS;
}
